import { ajax, tools } from './ajax.js';

//#region 切换显示的部分
let items = document.querySelectorAll('.list-group-item');
console.log('分组元素：', items);

function switchMode(mode) {
  if (mode == 1) {
    items[1].style.display = 'block';
    items[2].style.display = 'none';
  } else {
    items[1].style.display = 'none';
    items[2].style.display = 'block';
  }
}

switchMode(2);
// 切换按钮
let spswitch = document.querySelectorAll('.switch-box span');
spswitch[0].addEventListener('click', () => {
  switchMode(1);
});

spswitch[1].addEventListener('click', () => {
  switchMode(2);
});

//#endregion

//#region 登录的部分
let txt_username = document.getElementById('txt_username');
let txt_password = document.getElementById('txt_password');
let btnReset = document.getElementById('btnReset');
let btnLogin = document.getElementById('btnLogin');
let btnReg = document.getElementById('btnReg');

btnLogin.addEventListener('click', () => {
  let user = {
    username: txt_username.value,
    password: tools.md5(txt_password.value),
  };

  ajax.post('/user/auth/login', user, (data) => {
    if (data.success) {
      location.href = 'main.html';
      return;
    }
    showToast(data.message);
  });
});

btnReset.addEventListener('click', () => {
  txt_username.value = '';
  txt_password.value = '';
  txt_username.focus();
});

btnReg.addEventListener('click', () => {
  location.href = 'reg.html';
});

//#endregion

//#region 邮箱登录的部分
let txt_email = document.getElementById('txt_email');
let txt_code = document.getElementById('txt_code');
let btnSendEmail = document.getElementById('btnSendEmail');

let btnEReset = document.getElementById('btnEReset');
let btnELogin = document.getElementById('btnELogin');
let btnEReg = document.getElementById('btnEReg');

btnELogin.addEventListener('click', () => {
  ajax.post(
    '/user/auth/emailLogin',
    {
      email: txt_email.value,
      info: txt_code.value,
    },
    (data) => {
      if (data.success) {
        location.href = 'main.html';
        return;
      }
      showToast(data.message);
    }
  );
});

btnEReg.addEventListener('click', () => {
  location.href = 'reg.html';
});

btnEReset.addEventListener('click', () => {
  txt_email.value = '';
  txt_code.value = '';
  txt_email.focus();
});

btnSendEmail.addEventListener('click', () => {
  ajax.post(
    '/tool/sendEmailCode',
    {
      email: txt_email.value,
    },
    (data) => {
      showToast(data.message);
    }
  );
});

//#endregion

//#region 信息弹出层的部分
let divToast = document.getElementById('divToast');
// querySelector是通过css选择器获取页面元素（只会返回一个）
let toastBody = document.querySelector('#divToast .toast-body');
// 创建toast对象
const toast = new bootstrap.Toast(divToast);

// 显示toast对话框
function showToast(message) {
  // 修改内容
  toastBody.innerHTML = message;
  // 显示
  toast.show();
}
//#endregion
